import {ChatState} from "../types";
import {ConversationData} from "@/model/chat";
import {getRecentFriend} from "@/api/friend";
import {FriendDTO} from "@/api/friend/types";
import {getRecentFriendIds} from "@/utils/localStorage";
import useStore from "@/store";
import {getRecentMsg} from "@/api/msg";
import {MsgQuery} from "@/api/msg/types";

const useChatStore = defineStore("useChatStore", {
    state: (): ChatState => ({
        chatType: 0,
        isToCoArtBoard: false,
        isVideoing: false,
        isVoice: false,
        currentConversation: {} as ConversationData,
        agreeFriendValidate: false,
        recentSingleList: [],
        recentGroupList: [],
        onlineUser: [],
        allConversation: [],
    }),
    actions: {
        setIsToCoArtBoard(flag: boolean) {
            this.isToCoArtBoard = flag;
        },
        setIsVideoing(flag: boolean) {
            this.isVideoing = flag;
        },
        setIsVoice(flag: boolean) {
            this.isVoice = flag;
        },
        setAgreeFriendValidate(flag: boolean) {
            this.agreeFriendValidate = flag;
        },
        setOnlineUser(data: any) {
            this.onlineUser = data;
        },
        setRecentSingleList() {
            const {user} = useStore();
            getRecentFriend({
                userId: user.id,
                recentFriendIds: getRecentFriendIds().split(","),
            } as FriendDTO).then(({data}) => {
                if (data.flag) {
                    console.log("recentSingleList==",data.data)
                    this.recentSingleList = data.data;
                }
            })
        },
        setCurrentConversation(roomId: string, conversationData: ConversationData) {
            const msgParams = {roomId: roomId, pageNum: 1, pageSize: 10} as MsgQuery;
            getRecentMsg(msgParams).then(({data}) => {
                if (data.code === 200) {
                    console.log("data",data)
                    // 获取分页总数据数，设置最后一页序号
                    msgParams.pageNum = Math.ceil(data.total / msgParams.pageSize);
                    getRecentMsg(msgParams).then(({data}) => {
                        if (data.code === 200) {
                            this.currentConversation = conversationData;
                            this.currentConversation.pageNum = msgParams.pageNum;
                            this.currentConversation.singleMsgList = data.rows;
                        }
                    });
                }
            })
        },
        getters: {},
        persist: {
            key: "chat",
            storage: sessionStorage,
        },
    },
});

export default useChatStore;
